package com.evendai.sipdemo.camera

import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.os.Build
import android.view.View
import android.view.ViewGroup
import cn.dazhou.railway.monitor.camera.ISipVideoView
import com.evendai.loglibrary.Timber
import com.evendai.sipdemo.BaseActivity
import com.evendai.sipdemo.Keys
import com.evendai.sipdemo.PersistentVariables
import com.evendai.sipdemo.databinding.ActivityCameraBinding
import com.evendai.sipdemo.util.SipUtil
import org.doubango.ngn.media.NgnProxyAudioProducer
import org.doubango.ngn.media.NgnProxyVideoProducer
import org.doubango.ngn.sip.NgnAVSession

class CameraActivity : BaseActivity(), ISipVideoView {

    private val binding: ActivityCameraBinding by lazy { ActivityCameraBinding.inflate(layoutInflater, getContentContainer(), true) }
    private lateinit var sipVideoPresenter: SipVideoPresenterImpl
    private var isInCall = false
    private var isManualStopCall = false
    /** 呼叫状态广播接收者 */
    private var mCallStateBroadcastReceiver : BroadcastReceiver? = null
    /** 是否是单呼视频 */
    private var isVideoMeeting = false
    /** 是否是创建视频会议 */
    private var outgoingNumber: String = ""
    /** 是否是创建视频会议 */
    private var isMainVideoMeeting = false
    private var mAVSession: NgnAVSession? = null

    private var onStopCameraPreviewReceiver: BroadcastReceiver? = object: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Timber.i("是用户手动停止了通话吗：$isManualStopCall")
            if (!isManualStopCall && !isFinishing) {
                // 预览画面已经没有了，而且视频界面没销毁，并且也不是用户手动停止的通话，则应该重启App
                Timber.i("没有预览画面了，即将重启App")
                showOneButtonDialog("没有预览画面了")
            }
        }
    }

    override fun initView() {
        setLoadingText("正在打开视频")
        supportActionBar?.hide()
    }

    override fun initListener() {
        registerReceiver(onStopCameraPreviewReceiver, IntentFilter(NgnProxyVideoProducer.ACTION_ON_STOP_CAMERA_PREVIEW))
        binding.flRemoteVideoContainer.setOnLongClickListener { showDialog() }
    }

    private fun showDialog(): Boolean {
        val items = arrayOf("开扬声器", "关扬声器", "开麦克风", "关麦克风", "开会议听说权限", "关会议听说权限", "只开会议听权限", "只开会议说权限")
        AlertDialog
                .Builder(this)
                .setItems(items) { _, which ->
                    when (which) {
                        0 -> sipVideoPresenter.setSpeakerphoneOn(true)  // 开扬声器
                        1 -> sipVideoPresenter.setSpeakerphoneOn(false) // 关扬声器
                        2 -> NgnProxyAudioProducer.sOnMute = false      // 开麦克风
                        3 -> NgnProxyAudioProducer.sOnMute = true       // 关麦克风
                        4 -> {
                            SipUtil.sendVideoMeetingListenPermission(true, PersistentVariables.videoMeetingNumber)
                            SipUtil.sendVideoMeetingSpeakPermission(true, PersistentVariables.videoMeetingNumber)
                        }
                        5 -> {
                            SipUtil.sendVideoMeetingListenPermission(false, PersistentVariables.videoMeetingNumber)
                            SipUtil.sendVideoMeetingSpeakPermission(false, PersistentVariables.videoMeetingNumber)
                        }
                        6 -> {
                            SipUtil.sendVideoMeetingListenPermission(true, PersistentVariables.videoMeetingNumber)
                            SipUtil.sendVideoMeetingSpeakPermission(false, PersistentVariables.videoMeetingNumber)
                        }
                        7 -> {
                            SipUtil.sendVideoMeetingListenPermission(false, PersistentVariables.videoMeetingNumber)
                            SipUtil.sendVideoMeetingSpeakPermission(true, PersistentVariables.videoMeetingNumber)
                        }
                    }
                }
                .create()
                .show()
        return true
    }

    override fun initData() {
        volumeControlStream = AudioManager.STREAM_VOICE_CALL // 设置音量控制为电话声音控制
        sipVideoPresenter = SipVideoPresenterImpl(this, this)
        outgoingNumber = intent?.getStringExtra(Keys.OUTGOING_NUMBER) ?: ""
        isVideoMeeting = SipUtil.isVideoMeeting(outgoingNumber)
        isMainVideoMeeting = SipUtil.isMainVideoMeeting(outgoingNumber)

        showLoading()

        if (outgoingNumber.isNotBlank()) {
            // 呼出电话
            Timber.i("拨出视频电话：$outgoingNumber")
            sipVideoPresenter.makeCall(outgoingNumber)
        } else {
            // 呼入电话
            NgnAVSession.getSession(intent.getLongExtra(Keys.AV_SESSION_ID, -1))?.let {
                sipVideoPresenter.acceptCall(it)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (mAVSession != null) {
            onInCall(mAVSession!!, true)
        }
    }

    override fun onInCall(avSession: NgnAVSession, force: Boolean) {
        this.mAVSession = avSession
        Timber.fi("onInCall时，isInCall = $isInCall, force = $force")
        hideLoading()
        // 如果正在显示着视频了,而且不是强制显示，则本次的显示请求无需处理
        if (isInCall && !force) return
        val remoteCameraView = avSession.startVideoConsumerPreview(binding.flRemoteVideoContainer, false)
        val localCameraView = avSession.startVideoProducerPreview()
        if (remoteCameraView == null && localCameraView == null) {
            Timber.i("onInCall时，获取不到预览View和远程View")
            return
        }

        Timber.i("onInCall时，localCameraView = $localCameraView，remoteCameraView = $remoteCameraView")

        isInCall = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            remoteCameraView?.let { showRemoteCameraVideo(it) }
            localCameraView?.let { showLocalCameraView(it) }
        } else {
            localCameraView?.let { showLocalCameraView(it) }
            remoteCameraView?.let { showRemoteCameraVideo(it) }
        }

        if (isVideoMeeting) {
            // 发消息打开听说权限
            SipUtil.requestVideoListenerAndSpeakPermission()

            // 发消息给主摄像头打开视频画面
            SipUtil.changeVideoMeetingType(false)
        }
    }

    override fun onInCallFail(failMsg: String) {
        hideLoading()
        Timber.fi("onInCallFail(${failMsg})")
        finish()
    }

    override fun onEndCall() {
        hideLoading()
        isInCall = false
        Timber.fi("onEndCall()")
        finish()
    }

    override fun isInCalling(): Boolean = isInCall

    /** 显示本地摄像头画面 */
    private fun showLocalCameraView(cameraView: View) {
        if (cameraView.parent is ViewGroup) {
            (cameraView.parent as ViewGroup).removeView(cameraView)
        }
        binding.flLocalVideoContainer.removeAllViews()
        binding.flLocalVideoContainer.addView(cameraView)
    }

    /** 显示远程摄像头画面 */
    private fun showRemoteCameraVideo(cameraView: View) {
        if (cameraView.parent is ViewGroup) {
            (cameraView.parent as ViewGroup).removeView(cameraView)
        }
        binding.flRemoteVideoContainer.removeAllViews()
        binding.flRemoteVideoContainer.addView(cameraView)
    }

    override fun onDestroy() {
        super.onDestroy()
        sipVideoPresenter.closeVideo()

        //SipUtil.changeVideoMeetingType(true)

        if (mCallStateBroadcastReceiver != null) {
            unregisterReceiver(mCallStateBroadcastReceiver)
            mCallStateBroadcastReceiver = null
        }
        onStopCameraPreviewReceiver?.let { unregisterReceiver(it) }
    }
}